﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RRSimulator.BlobManager.Lib.Model
{
    public delegate void FileBlocksCompletedEventHandler(object sender, string fileName);

    public class BlocksModel : ObservableCollection<BlockModel>
    {
        public BlocksModel()
            :base()
        {
            InitBlocksInfo();
        }

        public event FileBlocksCompletedEventHandler FileBlocksCompleted;

        public string FileName { get; set; }
        public FileBlocksState FileBlocksState { get; set; }
        public bool IsFailed
        {
            get { return this.FirstOrDefault(b => b.IsFailed) != null; }
        }

        public bool IsCompleted
        {
            get { return this.FirstOrDefault(b => !b.IsCompleted) == null; }
        }

        private void InitBlocksInfo()
        {
            FileBlocksState = FileBlocksState.None;
            this.CollectionChanged += BlocksModel_CollectionChanged;
        }

        private void BlocksModel_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add && e.NewItems != null)
            {
                foreach (var item in e.NewItems)
                {
                    (item as BlockModel).BlockCompleted += BlocksModel_BlockCompleted;
                }
            }
            else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove && e.OldItems != null)
            {
                foreach (var item in e.OldItems)
                {
                    (item as BlockModel).BlockCompleted -= BlocksModel_BlockCompleted;
                }
            }
        }

        private void BlocksModel_BlockCompleted(object sender, string BlockId)
        {
            if (!IsFailed && IsCompleted && FileBlocksState == FileBlocksState.Uploaded && FileBlocksCompleted != null)
            {
                FileBlocksCompleted(this, FileName);
            }
        }
    }

    public enum FileBlocksState { None, Uploading, Uploaded }
}
